package P047_EqualsClass;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * equals 使用getClass进行类别判断
 *
 * @author xufy1
 */
public class EqualsClass {

    /**
     * instanceof 会判断该对象是否属于指定类或接口，同时也会判断是否属于其继承类或实现类。如果满足其中一个条件则返回值为 true，否则为 false。
     *
     *
     */
    @Test
    public void test1() {
        Employee e1 = new Employee("张三",100);
        Employee e2 = new Employee("张三",1001);

        Person p1= new Person("张三");
        //调用父类Persion的equals方法进行判断(instanceof 检查e1,由于继承)
        System.out.println("值判断 : " + p1.equals(e1));
        System.out.println("反过来，值判断 : " + e1.equals(p1));
        System.out.println("值判断 : " + p1.equals(e2));
        //id 不相等
        System.out.println("值判断 : " + e1.equals(e2));

        //问题： p1==e1  p1==e2  ,根据传递性原则：e1==e2

    }
}

class Person {

    private String name;

    public Person(String _name) {
        name = _name;
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object obj) {
        /**
         *  instanceof 实现策略：
         *@see  https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-6.html#jvms-6.5.instanceof
         *@see  https://www.cnblogs.com/ysocean/p/8486500.html
         */
        if (obj instanceof Person) {
            Person p = (Person) obj;
            if (p.getName() == null || name == null) {
                return false;
            } else {
                return name.equalsIgnoreCase(p.getName());
            }
        }
        return false;
    }
    //满足传递性原则
    /*@Override
    public boolean equals(Object obj) {

        if (obj !=null && obj.getClass()==this.getClass()) {
            Person p = (Person) obj;
            if (p.getName() == null || name == null) {
                return false;
            } else {
                return name.equalsIgnoreCase(p.getName());
            }
        }
        return false;
    }*/

    public boolean equalllls(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return name.equals(person.name);
    }
}
class Employee extends Person{
    private int id;
    public Employee(String _name,int _id){
        super(_name);
        id=_id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public boolean equals(Object obj){
        if(obj instanceof  Employee){
            Employee e=(Employee) obj;
            return super.equals(obj) && e.getId()==id;
        }
        return false;
    }
   /* @Override
    public boolean equals(Object obj){
        if(obj !=null && obj.getClass()==this.getClass()){
            Employee e=(Employee) obj;
            return super.equals(obj) && e.getId()==id;
        }
        return false;
    }*/
}
